'use server';

import { auth } from '@/lib/auth';
import { gorse } from '@/lib/gorse';
import { result, withZod } from '@/lib/utils';
import { revalidatePath } from 'next/cache';
import { headers } from 'next/headers';
import { z } from 'zod';

export const banUnbanUser = withZod(
  z.object({
    userId: z.string(),
    banned: z.boolean(),
  }),
  async ({ userId, banned }) => {
    try {
      banned
        ? await auth.api.banUser({
            body: {
              userId,
            },
            headers: await headers(),
          })
        : await auth.api.unbanUser({
            body: {
              userId,
            },
            headers: await headers(),
          });
      revalidatePath('/admin/user');
      return result();
    } catch (error) {
      return result(error, '操作失败');
    }
  },
);

export const signUpUser = withZod(
  z.object({
    email: z.string().email(),
    password: z.string().min(6),
    username: z.string(),
    name: z.string(),
  }),
  async ({ email, password, username, name }) => {
    try {
      const res = await auth.api.signUpEmail({
        body: {
          email,
          password,
          username,
          name,
        },
      });
      gorse.insertUsers([res.user.id]);
      return result();
    } catch (error) {
      return result(error, '注册失败');
    }
  },
);
